//
//  YZMRotationViewController.m
//  YZMicroStock
//
//  Created by apple on 17/4/5.
//  Copyright © 2017年 cqjr. All rights reserved.
//

#import "YZMRotationViewController.h"
#import "YZMAppDelegate.h"
#import "YZMRotationInforView.h"
#import "timeModel.h"
#import "GetCurrentTime.h"
#import "YZClient.h"
#import "YZMEntrustQueueView.h"
#import "YZMTrendView.h"
#import "YZMTrendItem.h"
#import "YZMTrendPacket.h"
#import "YZMKLineView.h"
#import <NSDate+DateTools.h>
#import "YZMKLinePacket.h"
#import "YZMKLineItem.h"
#import "MBProgressHUD+Utils.h"

@interface YZMRotationViewController ()<UIScrollViewDelegate>{
    timeModel *timemodel;
    NSTimer *timer;
}
@property (nonatomic, strong) YZMRotationInforView *inforView;
@property (nonatomic, copy) NSString *stockCode;
@property (nonatomic, assign) NSInteger segmentIndex;
@property (nonatomic, strong) NSTimer *inforTimer;
@property (nonatomic, strong) YZMStockRealModel *stockReal;
@property (nonatomic, assign) BOOL unShowErrorFlag;
@property (nonatomic, strong) UISegmentedControl *segment;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) YZMEntrustQueueView *queueView;
@property (nonatomic, strong) YZMTrendView *trendView;
@property (nonatomic, strong) YZMTrendPacket *trendPacket;
@property (nonatomic, strong) YZMKLineView *kLineView;
@property (nonatomic, strong) YZMKLinePacket *kLinePacket;
@property (nonatomic, strong) YZMKLineView *weekLineView;
@property (nonatomic, strong) YZMKLineView *monthKlineView;
@property (nonatomic, strong) YZMKLinePacket *weekkLinePacket;
@property (nonatomic, strong) YZMKLinePacket *monthkLinePacket;

@end

@implementation YZMRotationViewController

- (id)init{
    
    if (self = [super init]) {
        
        self.trendPacket = [[YZMTrendPacket alloc] init];
        self.kLinePacket = [[YZMKLinePacket alloc] init];
        self.weekkLinePacket = [[YZMKLinePacket alloc]init];
        self.monthkLinePacket = [[YZMKLinePacket alloc]init];
    }
    
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;

    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    YZMAppDelegate * appDelegate = (YZMAppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotation = YES;
    [self setNewOrientation:appDelegate.allowRotation];
    [self createObj];
    [self updateTime];
}



- (void)statusBarOrientationChange:(NSNotification *)noti{
    
    if (iPhoneX) {
        UIInterfaceOrientation newOrientation = [[noti.userInfo valueForKey:UIApplicationStatusBarOrientationUserInfoKey] integerValue];
        
        if (newOrientation == UIInterfaceOrientationLandscapeLeft) {
            [self.trendView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.height.equalTo(self.scrollView);
                make.left.equalTo(self.scrollView).with.offset(44);
                make.right.equalTo(self.queueView.mas_left).offset(-10);
            }];
        }else if(newOrientation == UIInterfaceOrientationLandscapeRight){
            self.queueView.backgroundColor = [UIColor redColor];
            [self.queueView mas_updateConstraints:^(MASConstraintMaker *make) {

                make.left.equalTo(self.scrollView.mas_left).with.offset(ScreenWidth-150);
                [self.queueView layoutIfNeeded];
            }];
            [self.trendView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.height.equalTo(self.scrollView);
                make.left.equalTo(self.scrollView.mas_left).with.offset(0);
                make.right.equalTo(self.queueView.mas_left).offset(-10);
            }];
        }
    }
    [self.trendView setNeedsDisplay];
    [self.kLineView setNeedsDisplay];
    [self.weekLineView setNeedsDisplay];
    [self.monthKlineView setNeedsDisplay];
}

//-(void)viewWillAppear:(BOOL)animated{

//    YZMAppDelegate * appDelegate = (YZMAppDelegate *)[UIApplication sharedApplication].delegate;
//    appDelegate.allowRotation = YES;
//    [self setNewOrientation:appDelegate.allowRotation];
//    [self createObj];
//}

#pragma mark UI
-(void)createObj{
    __weak typeof(&*self) safeSelf = self;
    self.inforView = [YZMRotationInforView new];
    [self.view addSubview:self.inforView];
    self.view.userInteractionEnabled = YES;
    [self.inforView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.top.equalTo(self.view);
        make.left.equalTo(self.view);
        if (iPhoneX) {
            make.left.equalTo(self.view).with.offset(44);
        }
        make.height.mas_equalTo(35);
    }];
    
    self.inforView.dismissBlock =^(){
        [YZMCMInstance dismissViewController];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"UpdateCurrentIndex" object:nil userInfo:@{@"currentIndex":@(safeSelf.segment.selectedSegmentIndex)}];
        [[NSNotificationCenter defaultCenter] removeObserver:safeSelf];
    };
    
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = [YZMAppStyle colorForMain];
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(44);
        make.top.equalTo(self.inforView.mas_bottom);
    }];
    
    self.segment = [[UISegmentedControl alloc] initWithItems: @[@"分时", @"日K", @"周K",@"月K",@"五档"]];
    [bgView addSubview: self.segment];
    
    self.segment.tintColor = [UIColor clearColor];
    [self.segment setBackgroundColor:[YZMAppStyle colorForMain]];
    NSDictionary* selectedTextAttributes = @{NSFontAttributeName:[YZMAppStyle mediumSizeFont],
                                             NSForegroundColorAttributeName:[YZMAppStyle colorForIconColor]};
    [self.segment setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];
    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[YZMAppStyle mediumSizeFont],
                                               NSForegroundColorAttributeName:[YZMAppStyle colorForMainTextColor]};
    [self.segment setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    
    self.segment.selectedSegmentIndex = self.segmentIndex;
    [self.segment addTarget: self action: @selector(segmentValueChanged:) forControlEvents: UIControlEventValueChanged];
    [self.segment setEnabled: YES forSegmentAtIndex: 0];
    [self.segment setEnabled: YES forSegmentAtIndex: 1];
    [self.segment setEnabled: YES forSegmentAtIndex: 2];
    [self.segment setEnabled: YES forSegmentAtIndex: 3];
    [self.segment setEnabled: NO forSegmentAtIndex: 4];
    [self.segment mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.bottom.equalTo(bgView);
        make.left.equalTo(bgView).offset(15);
        make.right.equalTo(bgView).offset(-15);
    }];
    
    self.scrollView = [[UIScrollView alloc] init];
    [self.view addSubview: self.scrollView];
    self.scrollView.pagingEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.delegate = self;
    self.scrollView.scrollEnabled = NO;
    self.scrollView.contentSize = CGSizeMake(ScreenHeight * 4, 0);
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(bgView.mas_bottom).offset(1);
        make.bottom.right.width.equalTo(self.view);
        make.left.equalTo(self.view);
        make.height.mas_equalTo(ScreenWidth-80);
    }];

    self.queueView = [[YZMEntrustQueueView alloc] init];
    [self.scrollView addSubview: self.queueView];
    [self.queueView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.scrollView);
        make.left.equalTo(self.scrollView).offset(ScreenHeight-110);
        make.width.mas_equalTo(100);
    }];

    self.trendView = [[YZMTrendView alloc] init];
    [self.scrollView addSubview: self.trendView];
    [self.trendView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.height.equalTo(self.scrollView);
        if (iPhoneX) {
            make.left.equalTo(self.scrollView).with.offset(44);
        }else{
             make.left.equalTo(self.scrollView);
        }
        make.right.equalTo(self.queueView.mas_left).offset(-10);
    }];

    self.kLineView  = [[YZMKLineView alloc] init];
    [self.scrollView addSubview: self.kLineView];
    [self.kLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.scrollView).offset(ScreenHeight);
        make.top.height.equalTo(self.scrollView);
        make.height.mas_equalTo(ScreenHeight*0.65);
//        make.width.mas_equalTo((ScreenWidth-80)/0.65);
        make.width.mas_equalTo(ScreenHeight);
    }];
    
    
    self.weekLineView  = [[YZMKLineView alloc] init];
    [self.scrollView addSubview: self.weekLineView];
    [self.weekLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.scrollView).offset(ScreenHeight*2);
        make.top.height.equalTo(self.scrollView);
        make.width.mas_equalTo(ScreenHeight);
    }];
    
    self.monthKlineView  = [[YZMKLineView alloc] init];
    [self.scrollView addSubview: self.monthKlineView];
    [self.monthKlineView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.scrollView).offset(ScreenHeight*3);
        make.top.right.height.equalTo(self.scrollView);
        make.width.mas_equalTo(ScreenHeight);
    }];

    [self.trendView updateFromDataPacket:self.trendPacket];
    [self.kLineView updateFromDataPacket:self.kLinePacket];
    [self.weekLineView updateFromDataPacket:self.weekkLinePacket];
    [self.monthKlineView updateFromDataPacket:self.monthkLinePacket];
    [self startTimer];
    
    if (self.segmentIndex) {
        
        [self autoAcrollViewToIndex];
    }
    
}

-(void)startTimer{
    
//    [self requestToLoadReal];
//    NSTimer *OnceTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(requestToLoadReal) userInfo:nil repeats:YES];
//    [[NSRunLoop mainRunLoop]addTimer:OnceTimer forMode:NSRunLoopCommonModes];
//    [OnceTimer fire];
//    [OnceTimer invalidate];
    if (self.inforTimer == nil) {
        
        self.inforTimer = [NSTimer timerWithTimeInterval: 3.0 target:self selector: @selector(requestToLoadReal) userInfo: nil repeats: YES];
        [[NSRunLoop mainRunLoop] addTimer: self.inforTimer forMode: NSRunLoopCommonModes];
        [self.inforTimer fire];
//        [self.inforTimer invalidate];
        
    }
}

- (void)segmentValueChanged: (UISegmentedControl *)segment{
    
    [self updateScrollViewFromSegment:segment];
}

- (void)updateScrollViewFromSegment:(UISegmentedControl *)segment{
    
    if (segment.selectedSegmentIndex !=0) {
        
        [self.segment removeSegmentAtIndex:4 animated:YES];
    }else{
        
        [self.segment insertSegmentWithTitle:@"五档" atIndex:4 animated:YES];
        [self.segment setEnabled: NO forSegmentAtIndex:4];
    }
    float screenWidth = [UIScreen mainScreen].bounds.size.width;
    [self.scrollView setContentOffset:CGPointMake(screenWidth*self.segment.selectedSegmentIndex, 0) animated:YES];
}

-(void)autoAcrollViewToIndex{
    
    if (self.segmentIndex) {
        
        [self.segment removeSegmentAtIndex:4 animated:YES];
    }else{
        
        [self.segment insertSegmentWithTitle:@"五档" atIndex:4 animated:YES];
        [self.segment setEnabled: NO forSegmentAtIndex:4];
    }
    
    [self.scrollView setContentOffset:CGPointMake(ScreenHeight*self.segmentIndex, 0) animated:YES];
}

- (void)stopTimer{
    
    if (self.inforTimer) {
        
        [self.inforTimer invalidate];
        self.inforTimer = nil;
    }
}

-(void)viewWillDisappear:(BOOL)animated{

    YZMAppDelegate * appDelegate = (YZMAppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotation = NO;
    [self setNewOrientation:NO];
    [timemodel removeObserver:self forKeyPath:@"timeString"];
    [timer invalidate];
    [self stopTimer];
}


- (void)requestToLoadReal{
    
    __weak typeof(&*self) safeSelf = self;
    
    [YZClient qt_getRealtimeInfoWithStockCodes:@[self.stockCode] success:^(NSURLResponse *response, id responseObject) {
    
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            NSDictionary *dict = topModel.data;
            if (!safeSelf.stockReal) {
                
                safeSelf.stockReal = dict[self.stockCode];
            }
            safeSelf.stockReal = dict[self.stockCode];
            [safeSelf.inforView updateWithStockCode:self.stockCode andStockName:self.stockReal.name];
            safeSelf.inforView.realStock = dict[self.stockCode];
            if ( [@(safeSelf.stockReal.price) isEqualGreaterThanDouble:0.0] ) {
                
                safeSelf.queueView.realItem = dict[self.stockCode];
                [safeSelf requestToLoadTrend];
                [safeSelf requestToLoadKLine];
                [safeSelf week_requestToLoadKLine];
                [safeSelf month_requestToLoadKLine];
                YZMStockRealModel *realInfo = dict[self.stockCode];
                self.trendPacket.closePrice  = realInfo.lastClosePrice;
                self.trendPacket.highPrice = realInfo.highPrice;
                self.trendPacket.lowPrice = realInfo.lowPrice;
                [self.trendView updateFromDataPacket: self.trendPacket];
            }
        }else{
            
            [safeSelf stopTimer];
            [topModel showMessage];
        }
        self.unShowErrorFlag = NO;
    } failure:^(NSError *error) {
        
        if (!self.unShowErrorFlag) {
            
            [error yz_showMessage];
        }
    }];
}

- (void)requestToLoadTrend{
    
    __weak typeof(&*self) safeSelf = self;
    NSString *beginTimeStr = nil;
    YZMTrendItem *lastItem = [self.trendPacket lastItem];
    if (lastItem) {
        
        beginTimeStr = [NSString stringWithFormat: @"%lld", lastItem.time];
    }
    NSString *code = [self codeAllaysValidate];
    [YZClient qt_getTrendInfoWithStockCode: code andBegin: beginTimeStr success:^(NSURLResponse *response, id responseObject) {
        YZGeneralResultModel *result = responseObject;
        
        if (result.success) {
            
            YZMTrendItem *newItem = [result.data lastObject];
            if (![newItem.code isEqualToString: safeSelf.stockCode]) {
                
                return ;
            }
            
            YZMTrendItem *currentLast = [safeSelf.trendPacket lastItem];
            if (currentLast) {
                
                [safeSelf.trendPacket updateFromItems: result.data];
            }
            else{
                
                [safeSelf.trendPacket setOriginItems: result.data];
            }
            [safeSelf.trendView updateFromDataPacket: safeSelf.trendPacket];
        }
    } failure:^(NSError *error) {
    
        [error yz_showMessage];
    }];
}


- (void)requestToLoadKLine{

    __weak typeof(&*self) safeSelf = self;
    NSDate *nowDate = [NSDate date];
    NSDate *startDate  = nil;
    BOOL append = self.kLinePacket.hasData;
    if (append) {
        
        startDate = [nowDate dateBySubtractingDays: 1];
    }else{
        
        startDate = [nowDate dateBySubtractingMonths: 4];
    }
    NSString *leTimeStr = [NSString stringWithFormat: @"%.0lf", startDate.timeIntervalSince1970 * 1000.0];
    NSString *geTimeStr =  [NSString stringWithFormat: @"%.0lf", nowDate.timeIntervalSince1970 * 1000.0];
    NSString *code = [self codeAllaysValidate];
    [YZClient qt_getKlineInfoWithStockCode: code andBegin: leTimeStr andEnd: geTimeStr success:^(NSURLResponse *response, id responseObject) {
        YZGeneralResultModel *result = responseObject;
        
        if (result.success) {
            YZMKLineItem *newItem = [result.data lastObject];
            if (![newItem.code isEqualToString: safeSelf.stockCode]) {
                
                return ;
            }

            if (append) {
                
                [safeSelf.kLinePacket updateFromItems: result.data];
            }else{
                
                [safeSelf.kLinePacket setOriginItems: result.data];
            }
            [safeSelf.kLineView updateFromDataPacket: safeSelf.kLinePacket];
        }
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];
}

- (void)week_requestToLoadKLine{
    
    __weak typeof(&*self) safeSelf = self;
    BOOL append = self.weekkLinePacket.hasData;
    
    NSString *code = [self codeAllaysValidate];
    [YZClient qt_getKlineInfoWithStockCode:code andType:@"weekKline" success:^(NSURLResponse *response, id responseObject) {
        
        YZGeneralResultModel *result = responseObject;
        if (result.success) {
            YZMKLineItem *newItem = [result.data lastObject];
            if (![newItem.code isEqualToString:safeSelf.stockCode]) {
                
                return;
            }
            
            if (append) {
                [safeSelf.weekkLinePacket updateFromItems: result.data];
            }
            else
            {
                [safeSelf.weekkLinePacket setOriginItems: result.data];
            }
            
            [safeSelf.weekLineView updateFromDataPacket: safeSelf.weekkLinePacket];
        }
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];
}

- (void)month_requestToLoadKLine{
    
    __weak typeof(&*self) safeSelf = self;
    BOOL append = self.monthkLinePacket.hasData;
    
    NSString *code = [self codeAllaysValidate];
    [YZClient qt_getKlineInfoWithStockCode:code andType:@"monthKline" success:^(NSURLResponse *response, id responseObject) {
        
        YZGeneralResultModel *result = responseObject;
        if (result.success) {
            YZMKLineItem *newItem = [result.data lastObject];
            if (![newItem.code isEqualToString:safeSelf.stockCode]) {
                
                return;
            }
            
            if (append) {
                
                [safeSelf.monthkLinePacket updateFromItems: result.data];
            }
            else{
                
                [safeSelf.monthkLinePacket setOriginItems: result.data];
            }
            
            [safeSelf.monthKlineView updateFromDataPacket: safeSelf.monthkLinePacket];
        }
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];
}

#pragma mark Screen rotation
- (void)setNewOrientation:(BOOL)fullscreen {
    
    if (fullscreen) {
        //不设置方向
        NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
        [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
        //强制向右横屏
        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
        
    }else{
        //不设置方向
        NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
        [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
        //强制竖屏
        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    }
}

#pragma mark time Update

-(void)updateTime{
    
    timemodel=[[timeModel alloc]init];
    [timemodel addObserver:self forKeyPath:@"timeString" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    self.inforView.timeLB.text=[NSString stringWithFormat:@"时间%@",[GetCurrentTime currenttime]];
    
    timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updatetime) userInfo:nil repeats:YES];
    
    [timer fire];
}

-(void)updatetime{
    
    timemodel.timeString=[GetCurrentTime currenttime];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"timeString"]&&object==timemodel) {
        self.inforView.timeLB.text=[NSString stringWithFormat:@"时间%@",timemodel.timeString];
        [change valueForKey:@"new"];
    }
}

- (void)updateWithParams: (NSDictionary *)params{
    
    self.stockCode  = params[@"stockCode"];
    self.segmentIndex = [params[@"index"] integerValue] - 100;
}


+ (instancetype)createWithParams: (NSDictionary *)params{
    
    YZMRotationViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

- (NSString *)codeAllaysValidate{
    
    NSString *code = self.stockCode;
    if (code.length == 0) {
        code = @"SH601318";
    }
    return code;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
